package org.springblade.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springblade.common.config.MqQueueConfig;
import org.springblade.common.config.MqttConfig;
import org.springblade.common.tool.DateTime;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.entity.Equipment;
import org.springblade.mapper.EquipmentMapper;
import org.springblade.mqtt.MqttHandle;
import org.springblade.service.IEquipmentService;
import org.springblade.vo.EquipmentVO;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * EquipmentServiceImpl
 * @author xxx
 */
@Service
public class EquipmentServiceImpl extends ServiceImpl<EquipmentMapper,Equipment> implements IEquipmentService {

	@Override
	public List<Equipment> getDeviceList(String type) {
		// 查询所有设备列表
		if (StringUtils.isBlank(type)){
			return this.list();
		}
		// 查询指定类型设备列表
		List<Equipment> list = this.list(Wrappers.<Equipment>lambdaQuery().eq(Equipment::getParentType, Integer.valueOf(type)));
		return list;
	}

	@Override
	public EquipmentVO getDeviceDetail(String equipmentId) {
		if (StringUtils.isBlank(equipmentId)){
			return new EquipmentVO();
		}

		EquipmentVO equipmentVO = new EquipmentVO();
		Equipment equipment = this.getOne(Wrappers.<Equipment>lambdaQuery().eq(StringUtils.isNotBlank(equipmentId), Equipment::getEquipmentId, equipmentId));
		String value = equipment.getValue();

		BeanUtil.copyProperties(equipment,equipmentVO);
		if (StringUtils.isNotBlank(value)){
			Map<String,Object> map = JSONObject.parseObject(value, Map.class);
			equipmentVO.setValuesMap(map);
		}
		return equipmentVO;
	}

	@Override
	public void pushDeviceStatus(EquipmentVO equipmentVO) {
		MqttHandle.publish(MqttConfig.MQTT_TOPIC_PROPERTIES, JSONObject.toJSONString(equipmentVO), 0);
	}

}
